<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\7\19 0019
 * Time: 17:52
 */
namespace app\api\model;
use think\Db;
use think\Model;
use think\Request;

class TopicModel extends Model
{
    /**获取一题
     * @param Request $request
     * @return array|bool|false|\PDOStatement|string|Model
     */
    public static function getTopic(Request $request){
        //验证数据
        $token = $request->param('token',null);
        if(!$token){
            return ['code'=>401,'msg'=>'参数错误'];
        }
        //验证token是否存在
        if(!$user = UserModel::istoken($token)){
            return ['code'=>402,'msg'=>'账号不存在'];
        }
        //随机获取题目
        $resul = Db::connect();
        $topicNum = $resul->name('topic_management')->count();
        if($topicNum<=0){
            return ['code'=>405,'msg'=>'没有题目'];
        }
        $num = mt_rand(1,$topicNum);
        $topic = $resul->name('topic_management')->limit($num-1,1)->select();
        //optional是json格式的数组，转化成数组
        $topic = $topic[0];
        $topic['optional'] = json_decode($topic['optional'],true);
        return ['code'=>200,'data'=>$topic];
    }
}